<?php
// Turn off all error reporting
error_reporting(0);
################## HEADERS   	########################
header("Cache-Control: no-cache, must-revalidate");
################## INCLUDES   	########################
################## FUNCTIONS   	########################
/**
encriptData - returns decrypted string
@$crypttext - encrypted string
*/
define("TRACE", false);
define("PR_KEY", "/etc/apache2/myssl/privkey.pem");
define("PR_PASS", "mir05mir");

function encriptData($crypttext){
	$crypttext = base64_decode($crypttext);
	$result = openssl_pkey_get_private(array("file://".PR_KEY, PR_PASS));
	if ($result) {
		
	} else {
		print "ERROR CODE 1011"; // "\nPrivate key NOT OK\n\n";
	}
	if (TRACE) {
		ob_start();	
		phpinfo () ;
		$pinfo = ob_get_contents () ;
		ob_end_clean () ;
		$fh = fopen("trace/licensetrace.html", 'w') or die("can't open file");
		fwrite($fh, $pinfo);
		fclose($fh);		
	}
	openssl_private_decrypt($crypttext, $newsource, $result);
	while ($msg = openssl_error_string()) {
		echo $msg;
		return;
	}

	// now we completed decrypting the request ,  the de-decripted request is in $newsource
	/*
	$newsource = ereg_replace("[\n\r]", "", $newsource);
	$newsource = ereg_replace("\t\t+", "", $newsource);
	$newsource = ereg_replace("[\"]", "'", $newsource);

	*/
	return $newsource;
}
################## PARAMETERS & VARIABLES ########################
$crypttext = $_REQUEST["license"];
$newsource = encriptData($crypttext);//decrypt incomming string with the private key
// $newsource = stripslashes($crypttext);
$error = false;
$errorCode = "NOERROR";
$rowdata = "NORECORD";

################## ACTIONS		########################

// $newsource = "<info id='1234567890' key='1234-5678-90'/>  <token value='Bzijf8el' id='127.0.0.1'/></license>";
/*
URL ENCODED EXAMPLE:
<license><info id="1237890" key="sbnd" /><token id="123" value="abctoken"/></license>
http://lab.genericframe.com/MXMLProxyServer/licensecheck.php?license=%3clicense%3e%3cinfo+id%3d%221237890%22+key%3d%22sbnd%22+%2f%3e%3ctoken+id%3d%22123%22+value%3d%22abctoken%22%2f%3e%3c%2flicense%3e

<info id='1234567890' key='1234-5678-90'/>  <token value='Bzijf8el' id='127.0.0.1'/></license>
http://lab.genericframe.com/MXMLProxyServer/licensecheck.php?%3cinfo+id%3d'1234567890'+key%3d'1234-5678-90'%2f%3e++%3ctoken+value%3d'Bzijf8el'+id%3d'127.0.0.1'%2f%3e%3c%2flicense%3e
*/


//READ XML
$dom = new DOMDocument('1.0', "utf-8");
$dom->preserveWhiteSpace = false;
$dom->formatOutput = TRUE;
$parameterHTML = htmlentities($newsource);
$dom->loadXML($newsource);
	
//xpath /license/info
$xp = new DomXPath($dom);//create xPath Object
$nodeList = $xp->query('/license/info');
if ($nodeList->length >= 1 ){
	$element = $nodeList->item(0);
	//get id
	if($element->hasAttribute('id')) {
		$licenseid = $element->getAttribute('id');
	}else{
		$error = true;
		$errorCode = 1021; //missing info:id
		$errorMsg = "Missing info:id";
	}
	//get key
	if($element->hasAttribute('key')) {
		$licensekey = $element->getAttribute('key');
	}else{
		$error = true;
		$errorCode = 1022;//missing info:key
		$errorMsg = "Missing info:key";
	}
}else{
	$error = true;
	$errorCode = 1031; //Missing TAG info
	$errorMsg = "Missing info";
}

//xpath /license/token
$xp = new DomXPath($dom);//create xPath Object
$nodeListToken = $xp->query('/license/token');
if ($nodeListToken->length >= 1 ){
	$elementToken = $nodeListToken->item(0);
	//get value
	if($elementToken->hasAttribute('value')) {
		$tokenValue = $elementToken->getAttribute('value');
	}else{
		$error = true;
		$errorCode = 1023; //Missing token:value
		$errorMsg = "Missing token:value";
	}
	//get id
	if($elementToken->hasAttribute('id')) {
		$tokenID = $elementToken->getAttribute('id');
	}else{
		$error = true;
		$errorCode = 1024; //missing token:id
		$errorMsg = "Missing token:id";
	}
}else{
	$error = true;
	$errorCode = 1032;//missing TAG token
	$errorMsg = "Missing TAG token";
}

$remote_ip = $_SERVER["REMOTE_ADDR"];

// CHECK DATABASE FOR LICENSES
//check the rights in the DB 
if (!$error){
	try {
		$dbh = new PDO('mysql:host=localhost;dbname=genericframe_licenses', 'dbuser', 'dbuser01');
		$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);//set error mode to through an exception
		// ##########################################
		$stmt = $dbh->prepare('SELECT * FROM `licenses` WHERE `key` = ?');
		$stmt->execute(array($licensekey));
		if ($row = $stmt->fetch()) {
			$rowdata = $row;
		}else{
			//no data found return FREE LICENSE
			$stmt = $dbh->prepare('SELECT * FROM `licenses` WHERE `key` = ?');
			$stmt->execute(array("free"));
			if ($row = $stmt->fetch()) {
				$rowdata = $row;
			}else{
				//no data found return FREE LICENSE
				$error = true;
				$errorCode = 2001;//no Data found
				$errorMsg = "SQL: No data fond!";			
			}
		}
		$dbh = null;
	} catch (PDOException $e) {
		$error = true;
		$errorCode = 2000;//SQL Error
		$errorMsg = "SQL Error! " . $e->getMessage();
	}
}
//WIRTE XML
$sendBackXML = new XmlWriter();
$sendBackXML->openMemory();	
if($error){
	$sendBackXML->startElement('error');
	$sendBackXML->writeAttribute('errorCode', $errorCode);
	$sendBackXML->writeAttribute('errorMsg', $errorMsg);
	$sendBackXML->endElement();
}else{
	$sendBackXML->startElement('node');
	$sendBackXML->writeAttribute('company', $rowdata[company]);
	$sendBackXML->writeAttribute('licenseType', $rowdata[key]);
	$sendBackXML->writeAttribute('verificationid', $tokenValue);

	$components = explode(",", $rowdata[components]);
	foreach($components as $component){
		$sendBackXML->startElement('product');
                $component = trim($component); // remove the blank's
		$sendBackXML->writeAttribute('id', $component);  
		$sendBackXML->endElement();
	}
	$sendBackXML->endElement();
}

$sendBack = $sendBackXML->outputMemory(true);

################## OUTPUT		########################
// echo "<br>INPUT:<br>".$parameterHTML;
// echo "<br>OUTPUT:<br>".htmlentities($sendBack);
echo $sendBack;
?>
